package mephisto.services.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import mephisto.Constants;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class HttpCallHandler {

    public InputStream callService(Map<String, Object> parameters, String methodType, String endpoint)
            throws IOException {

        GetMethod get = new GetMethod(endpoint);

        NameValuePair[] nvp = new NameValuePair[parameters.size()];

        Iterator<String> it = parameters.keySet().iterator();
        for (int i = 0; it.hasNext(); i++) {
            String key = it.next();
            nvp[i] = new NameValuePair(key, (String) parameters.get(key));
        }
        get.setQueryString(nvp);
        get.setDoAuthentication(false);
        HttpClient client = new HttpClient();

        int status = client.executeMethod(get);
        InputStream is = get.getResponseBodyAsStream();
        return is;
    }

    public InputStream callBasicAuthService(Map<String, Object> parameters, String endpoint) throws Exception {

        HttpClient client = new HttpClient();
        URL url = new URL(endpoint);
        String host = url.getHost();
        int port = url.getPort();
        String protocol = url.getProtocol();
        if (!protocol.equals("http")) {
            throw new Exception("Unsupported protocol exception.");
        }

        String user = (String) parameters.get(Constants.USER);
        String password = (String) parameters.get(Constants.PASSWORD);
        client.getState().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));

        GetMethod get = new GetMethod(endpoint);

        NameValuePair[] nvp = new NameValuePair[parameters.size()];

        Iterator<String> it = parameters.keySet().iterator();

        for (int i = 0; it.hasNext(); i++) {
            String key = it.next();
            nvp[i] = new NameValuePair(key, (String) parameters.get(key));
        }
        get.setQueryString(nvp);
        get.setDoAuthentication(true);
        InputStream is = null;

        int status = client.executeMethod(get);
        is = get.getResponseBodyAsStream();

        return is;

    }

  
}
